<template>
  <Start @handler="handlers" :email="email" :se="se" @sendMsg="sendMsg" />
</template>

<script setup lang="ts">
import { getRegisterAPI, getEmailSmsAPI } from '@/request/index'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { sha256 } from 'js-sha256'
import { ref } from 'vue'

const router = useRouter()

const email = ref(false)
const se = ref(60)

// 用户点击发送验证码
const sendMsg = async (event:MouseEvent, num:Array<{ value:string }>) => {
  if (email.value) return

  // 检查邮箱是否输入
  if (!/\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/.test(num[1].value)) {
    ElMessage.warning("邮箱格式错误！")
    return
  }

  // 发送验证码
  email.value = true;
  (event.target as HTMLElement).style.backgroundColor = "rgb(22, 162, 184)"

  let ses = setInterval(() => {
    se.value--
    if (se.value == 0) {
      clearInterval(ses)
      email.value = false;
      (event.target as HTMLElement).style.backgroundColor = "rgb(8, 131, 149)"
      se.value = 60
    }
  }, 1000)

  // 邮箱发送给后端
  const data = await getEmailSmsAPI(num[1].value)
  if (data != null) ElMessage.success("验证码已发送至您的邮箱")

  if ((data as any).code == 10000) {
    sessionStorage.setItem("secb", data.data)
  } else ElMessage.warning((data as any).msg)
}

const handlers = async (num:Array<{ value:string }>) => {
  // 处理注册逻辑

  // 检查输入是否有问题
  if (!num.some(item => item.value.length != 0)) {
    ElMessage.warning("输入不得为空！")
    return
  }

  // 检查用户名是否少于6个字符
  if (num[0].value.length < 3) {
    ElMessage.warning("用户名不得少于3个字符！")
    return
  }
  
  // 检查邮箱
  if (!/\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/.test(num[1].value)) {
    ElMessage.warning("邮箱格式错误！")
    return
  }

  // 检查密码
  const categories = [
    /[A-Z]/,
    /[a-z]/,
    /\d/,
    /[^A-Za-z0-9]/
  ]

  if (!(categories.filter(regex => regex.test(num[2].value)).length >= 3)) {
    ElMessage.warning("密码必须包含大小写字母、特殊字符、数字等其中三个！")
    return
  }

  // 检查重复密码
  if (num[3].value != num[2].value) {
    ElMessage.warning("重复密码和输入密码不同！")
    return
  }

  // 检查验证码
  if (num[1].value != sessionStorage.getItem("secb")) {
    ElMessage.warning("验证码输入错误！")
    return
  }

  // sha256加密一波
  num[2].value = sha256(num[2].value)
  num[3].value = sha256(num[3].value)

  // // 调用接口，并提示注册成功
  const data = await getRegisterAPI(num[0].value, num[2].value, num[1].value)
  if ((data as any).code == 10000) {
    ElMessage.success("注册成功！")
    router.push('/login')
  } else ElMessage.warning((data as any).msg)
}
</script>

<style lang="less" scoped>

</style>